package com.d404.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import im.beans.Group;
import im.beans.GroupMessage;
import im.beans.Group_User;
import im.beans.User;
import manager.PersistentManager;

/**
 * Servlet implementation class GetGroupMessage
 */
//@WebServlet("/GetGroupMessage")
public class GetGroupMessage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetGroupMessage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		
		String data = request.getParameter("data");
		Upload upload = JSON.parseObject(data,Upload.class);
		
		Download download = new Download();
		download.setMsgs(new ArrayList<SendGroupMessage.Upload>());
		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();
		try{
			
			// 上次读取时间
			long BeforeTime = System.currentTimeMillis();
			Group_User before = null;
			Query qTime = session.createQuery("from Group_User gu where gu.group = ? and gu.user = ?");
			Group group = new Group();
			group.setId(upload.getGroupID());
			qTime.setParameter(0, group);
			User user = new User();
			user.setId(upload.getUserID());
			qTime.setParameter(1, user);
			List<Group_User> gus = qTime.list();
			for(Group_User gu:gus)
			{
				before = gu;
			}
			
			BeforeTime = before.getLastReadMsgTimeStamp();
			Query q = session.createQuery("from GroupMessage gm where gm.timestamp > ? and gm.groupId = ?");
			q.setParameter(0, BeforeTime);
			q.setParameter(1, upload.getGroupID());
		    List<GroupMessage> gms =  q.list();
		    for(GroupMessage gm:gms)
		    {
		    	
		    	//跳过自己发的消息
		    	if (gm.getUserId() == upload.getUserID()) {
					continue;
				}
		    	
		    	SendGroupMessage.Upload gmU = new SendGroupMessage.Upload();
		    	gmU.setFileName(gm.getFileName());
		    	gmU.setFileURI(gm.getFileURI());
		    	gmU.setFromID(gm.getUserId());
		    	gmU.setFromName(gm.getUserName());
		    	gmU.setGroupID(gm.getGroupId());
		    	gmU.setGroupName(gm.getGroupName());
		    	gmU.setText(gm.getMessage());
		    	gmU.setTimestamp(gm.getTimestamp());
		    	gmU.setType(Long.parseLong(gm.getType()));
		    	gmU.setRealName(gm.getRealName());
		    	
		    	if(gmU.getTimestamp() > BeforeTime)
		    	{
		    		BeforeTime = gmU.getTimestamp();
		    	}
		    	
		    	download.getMsgs().add(gmU);
		    }
		    before.setLastReadMsgTimeStamp(BeforeTime);
		    
		    session.getTransaction().commit();
	    	download.setStatus(Download.SUCCESS);
			
		}catch(Exception e)
		{
			tx.rollback();
			download.setStatus(Download.FAILED);
			e.printStackTrace();
		}finally {
//			session.close();
		}
		
		System.out.println(JSON.toJSONString(download));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(JSON.toJSONString(download));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	// 上行数据
    public static class Upload
    {
        long userID;
        String userName;
        long groupID;

        public long getUserID() {
            return userID;
        }

        public void setUserID(long userID) {
            this.userID = userID;
        }

        public long getGroupID() {
            return groupID;
        }

        public void setGroupID(long groupID) {
            this.groupID = groupID;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

    // 下行数据
    public static class Download
    {
        public static final int SUCCESS = 1;
        public static final int FAILED = 2;
        int status;
        ArrayList<SendGroupMessage.Upload> msgs;

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public ArrayList<SendGroupMessage.Upload> getMsgs() {
            return msgs;
        }

        public void setMsgs(ArrayList<SendGroupMessage.Upload> msgs) {
            this.msgs = msgs;
        }
    }

}
